//index.js
//获取应用实例
const app = getApp()
var util = require('../../utils/util.js');
Page({
  data: {
    PageCur: 'index',
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    motto: 'Hi 开发者！',
    userInfo: {},
    visitTotal: 0,
    starCount: 0,
    forksCount: 0,
    hasUserInfo: false,
    projectList: [],
    projectListTotal: [],
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    myDict: {
      "priority":[
        {"code":"1","name":"高"},
        {"code":"2","name":"中"},
        {"code":"3","name":"低"}
      ],
      "status":[
        {"code":"1","name":"待发布"},
        {"code":"2","name":"待完成"},
        {"code":"3","name":"待验收"},
        {"code":"4","name":"内部验收"},
        {"code":"5","name":"取消"}
      ]
    }
  },
  compPriority: function(priority){
    let txt = "";
    this.data.myDict.priority.forEach((element)=>{
      if(element.code == priority){
        txt = element.name;
      }
    });
    return txt;
  },
  compStatus: function(status){
    let txt = "";
    this.data.myDict.status.forEach((element)=>{
      if(element.code == status){
        txt = element.name;
      }
    });
    return txt;
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  coutNum(e) {
    var a = 100000000;
    if (e > a) {
      e = (e / a * 10000).toFixed(1) + '万'
    }
    return e
  },
  gotoProjectInfo(e){
    // console.log(e.target.dataset.project);
    // console.log(e.currentTarget.dataset.project);
    wx.navigateTo({
      url: '../tasks/tasks?project='+JSON.stringify(e.target.dataset.project)
    })
  },
  filterList(e){
    console.log(e.detail);
    let arr = [];
    if(e.detail === ""){
      this.setData({
        projectList: this.data.projectListTotal
      });
    }else{
      this.setData({
        projectList: this.data.projectListTotal.filter((element)=>{
          return element.projectName.indexOf(e.detail) >= 0;
        })
      });
    }
  },
  onRequestSubscribeMessage(){
    wx.requestSubscribeMessage({
      tmplIds: ['rVbAwumvII-_UEB5dNNMyoFOw4ZqJLjqsGXStBOjNx4'],
      success (res) {
        console.log("订阅消息：", res);
      }
    });
  },
  getTaskList(){
    /**
     * 获取每日任务列表
    */
    app.AjaxPost({
      p0: {
        appName: "s6-service",
        methodName: "findTaskListByPage",
        params: {
          beCTask: [false],
          beCustomer: false,
          creator: null,
          gerentUser: null,
          name: null,
          pageNumber: 1,
          pageSize: 20,
          priority: [],
          projectId: null,
          queryType: 1,
          status: [],
          versionId: null
        },
        serviceName: "dailyWorkbenchService",
        uitype: "CustomServiceReqVO",
      },
      servicename: "customService"
    }, (res)=>{
      console.log("列表数据返回：", res)
      if(res){
        let _this = this;
        /**
         * 数据动画效果
        */
        let taskTotal = 0;
        let todayTotal = 0;
        res.forEach((element)=>{
          if(element.taskSeq <= 5){
            taskTotal += 1;
            todayTotal += 1;
          }
          element.priorityTxt = _this.compPriority(element.priority);
          element.statusTxt = _this.compStatus(element.status);
        });
        _this.setData({
          projectList: res || [],
          projectListTotal: res || []
        });
        let i = 0;
        var numDH = () => {
          if (i < 5) {
            setTimeout(() => {
              _this.setData({ starCount: i, forksCount: i, visitTotal: i})
              i++
              numDH();
            }, 50)
          } else {
            _this.setData({
              visitTotal: _this.coutNum(res.length),
              starCount: _this.coutNum(taskTotal),
              forksCount: _this.coutNum(todayTotal)
            })
          }
        }
        numDH();
      }
    });
  },

  SignIn(e){
    let unikey = util.unikey[wx.getStorageSync('username')];
    let location = {
      "lng": "103.970" + (Math.ceil(Math.random()*100) + 200),
      "lat": "30.676" + (Math.ceil(Math.random()*450) + 200)
    };
    let appdate = Object.assign({},JSON.parse(e.currentTarget.dataset.appdate), location);
    wx.showModal({
      title: '提示',
      content: '确定是否' + e.currentTarget.dataset.txt + '签到？',
      success (res) {
        if (res.confirm) {
          wx.showLoading({ title: '签到中',})
          wx.request({
            url: "https://verp6.vworkcloud.com/thornGwt.vue/thornGwt.vue",
            method: "POST",
            data: {
              "servicename": "executeCustom",
              "p0": {
                "appName": "p6-service",
                "serviceName": "wxDispatchService",
                "methodName": "appletClockIn",
                "params": {
                  "action": "appletClockIn",
                  "data": { "head": { "unikey": unikey }, "body": { "appDate": appdate } }
                }
              }
            },
            success(res) {
              console.log("签到：", res)
              wx.hideLoading();
              wx.showToast({ title: "操作完成", icon: 'none', duration: 2000, mask: true});
            }, 
            fail(err) {
              wx.hideLoading();
              wx.showToast({ title: "请求失败", icon: 'none', duration: 2000, mask: true })
              console.log("err",err);
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  
  // 开工
  startWorks(e){
    let ids = e.currentTarget.dataset.task.id;
    let myMethodName = e.currentTarget.dataset.methodname || "updateTaskSeq"; // 开工状态
    app.AjaxPost({
      p0: {
        appName: "s6-service",
        methodName: myMethodName,
        params: {
          action: e.currentTarget.dataset.type,
          taskIds: [ids]
        },
        serviceName: "dailyWorkbenchService",
        uitype: "CustomServiceReqVO"
      },
      servicename: "customService"
    }, (res)=>{
      console.log("用户点击返回：", res)
      let _this = this;
      _this.getTaskList();
    });
  },

  onLoad: function() {
  },
  onShow: function(){
    this.getTaskList();
    this.setData({
      username: wx.getStorageSync('username')
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getTaskList();
    wx.showNavigationBarLoading(); //在标题栏中显示加载图标
  },
})
